import Vue from "vue";
import Vuex from "vuex";
import {getMenuList} from "@/api"

//引入allRoutes
import allRoutes from "../router/allRouters"
//引入递归函数
import recursionRoutes from "../Utils/recursionRoutes"
//引入动态路由daynamicRoutes
import daynamicRoutes from "../router/dynamicRoutes"
import dynamicRoutes from "../router/dynamicRoutes";
//引入router
import router from "../router"
Vue.use(Vuex);
//刷新页面会丢失用户信息，所以要从localStotrage中取
let userInfo=localStorage.getItem("login-userInfo") || "{}"
userInfo=JSON.parse(userInfo)
export default new Vuex.Store({
  state: {
    userInfo, //用户信息
    menuList:[], //定义用户侧边菜单栏,后台返回的数据和allRouters做对比得到的数据，和菜单栏匹配的路由
    crumbs:[]
  },
  mutations: {
    //更改userInfo
    SET_USERINFO(state,payload){
      state.userInfo=payload;
    },
    SET_MENULIST(state,payload){
      state.menuList=payload  //和菜单栏匹配的路由
      console.log( state.menuList);
      
      //1.将menuList（和菜单栏匹配的路由）赋值给dynamicRoutes中的children
      let target=dynamicRoutes.find(item=>item.path==="/")
      target.children=[...state.menuList] //扩展运算符，将state.menuList数组分解，再放入数组
      //console.log(dynamicRoutes);
      //动态添加配置到router中//动态的将路由添加到，router中，核心方法router.addRoutes(参数为符合路由规则的数组)
      router.addRoutes(dynamicRoutes)
    },
    //设置面包屑
    SET_CRUMBS(state,payload){
      state.crumbs=payload
    }
},
  
  actions: {
  async FETCH_MENULIST({commit}){
      //1.发送请求，获取用户菜单数据
      let userMenu=await getMenuList()
      //console.log(userMenu);
      //2.通过allRoutes和请求就来的用户菜单数据进行对比，获取和菜单栏匹配的路由
      let sideMenu= recursionRoutes(allRoutes,userMenu.data.menuList)
     // console.log(sideMenu);
      //将数据结果提交到mutation
      commit('SET_MENULIST',sideMenu)
    }
  },
  modules: {}
});
